package cn.jingyuan.swan.cloud.oauth2;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户详情
 */
public class DefaultUserDetails implements UserDetails, CredentialsContainer {

    /** 用户ID */
    @Getter
    @Setter
    private Long userId;

    /** 登录名 */
    @Getter
    @Setter
    private String username;

    /** 密码 */
    @JsonIgnore
    @Getter
    @Setter
    private String password;

    /** 用户权限 */
    @Setter
    private Collection<? extends GrantedAuthority> authorities;

    /** 是否已锁定 */
    @Setter
    private boolean accountNonLocked;

    /** 是否已过期 */
    @Setter
    private boolean accountNonExpired;

    /** 是否启用 */
    @Setter
    private boolean enabled;

    /** 密码是否已过期 */
    @Setter
    private boolean credentialsNonExpired;

    /** 认证客户端ID */
    @Getter
    @Setter
    private String clientId;

    /** 昵称 */
    @Getter
    @Setter
    private String nickName;

    /** 头像 */
    @Getter
    @Setter
    private String avatar;

    /** 账户Id */
    @Getter
    @Setter
    private Long accountId;

    /***账户类型     */
    @Getter
    @Setter
    private String accountType;

    /** 用户附加属性 */
    @Setter
    private Map<String, Object> attrs;

    /**
     * 只是客户端模式，不包含用户信息
     */
    public Boolean isClientOnly() {
        return clientId != null && username == null;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities == null) {
            return Collections.emptyList();
        }
        return this.authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

    public Map<String, Object> getAttrs() {
        if (attrs == null) {
            return new HashMap<>(16);
        }
        return attrs;
    }

    @Override
    public void eraseCredentials() {
        password = null;
    }

}
